﻿using AopFilters.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AopFilters
{
    public class AopScope
    {
        public List<Func<Task>> CommitEvents = new List<Func<Task>>();
        public int _id;
        public AopModuleInfo _info;
        ILogger<AopScope> _logger;
        //构造函数注入依赖的服务...
        public AopScope(ILogger<AopScope> logger)
        {
            _logger = logger;
        }

        public AopScope Begin(int id)
        {
            _id = id;
            return this;
        }

        private Task InvokeBefore()
        {
            _logger.LogInformation($"action执行前... id:'{_id}'");
            //初始化需要的数据
            _info = new AopModuleInfo { Id = _id, Name = "km", CreateTime = DateTime.Now };
            return Task.CompletedTask;
        }

        public async Task Invoke(Func<AopScope,Task> func)
        {
            //开启事务
            try
            {
                await InvokeBefore();
                await func.Invoke(this);
                await InvokeAfter();
                //提交事务
            }
            catch (Exception)
            {
                //回滚事务
                throw;
            }
            CommitEvents.ForEach(async x => await x());
        }

        private Task InvokeAfter()
        {
            _logger.LogInformation($"action执行后... id:'{_id}'");
            return Task.CompletedTask;
        }

        public void OnCommit(Func<Task> func)
        {
            CommitEvents.Add(func);
        }
    }
}
